package com.idreems.zakerlike;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import opens.components.http.ChannelRequest;
import opens.components.http.core.RequestQueue;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.flurry.android.FlurryAgent;
import com.huewu.pla.pinterest.PinterestActivity;
import com.idreems.ad.YoumiOfferwallActivity;
import com.idreems.model.ComicServerData;
import com.idreems.model.GifServerData;
import com.idreems.model.JionServerData;
import com.idreems.model.MeaningEpisodes;
import com.idreems.model.MengServerData;
import com.idreems.model.QiushiImages;
import com.idreems.model.QiushiLatest;
import com.idreems.model.ServerDataDecoder;
import com.idreems.model.WeiboHumer;
import com.idreems.zakerlike.util.Util;
import com.idreems.zakerlike.view.FixedGridLayout;
import com.idreems.zakerlike.view.MyViewGroup;
import com.idreems.zakerlike.view.MyViewGroup.ScrollToScreenCallback;
import com.idreems.zakerlike.view.Rotate3dAnimation;

public class HappyTimesActivity extends BaseActivity implements ScrollToScreenCallback, android.view.View.OnClickListener {
    private static final boolean kTestMode = false;

    private TextView pageinfo_num;
    private LinearLayout pageinfo;
    private LinearLayout tool;
    private MyViewGroup myViewGroup;
    private String mStrChannel = "";
    private ArrayList<String> mDisplayed = new ArrayList<String>();
    private ArrayList<String> mHided = new ArrayList<String>();
    int curScreen = 1;
    HashMap<String, Class<?>> channel2ClassHashMap = new HashMap<String, Class<?>>();
    {
        channel2ClassHashMap.put(new JionServerData().title(), JionServerData.class);
        channel2ClassHashMap.put(new GifServerData().title(), GifServerData.class);
        channel2ClassHashMap.put(new MengServerData().title(), MengServerData.class);
        channel2ClassHashMap.put(new ComicServerData().title(), ComicServerData.class);
        channel2ClassHashMap.put(new WeiboHumer().title(), WeiboHumer.class);// 微博笑典
        channel2ClassHashMap.put(new MeaningEpisodes().title(), MeaningEpisodes.class);// 内涵段子
        channel2ClassHashMap.put(new QiushiImages().title(), QiushiImages.class);
        channel2ClassHashMap.put(new QiushiLatest().title(), QiushiLatest.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FlurryAgent.onEndSession(this);
    }
    /**
     * show tapjoy offerwall
     */
    private void initOfferwall()
    {
//    	Hashtable<String, String> flags = new Hashtable<String, String>();
//		flags.put(TapjoyConnectFlag.ENABLE_LOGGING, "false");
//    	TapjoyConnect.requestTapjoyConnect(getApplicationContext(), "8ad5d029-6043-47f6-9c10-6d9c99b4d6da", "S11MnpTBwUjBqBsJTqJD", flags);
    	
    }
    
    private void showOfferwall(long delayMillis)
    {
    	new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
//				TapjoyConnect.getTapjoyConnectInstance().showOffers();
			}
		}, delayMillis);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        FlurryAgent.onStartSession(this, Util.kFlurryKey);
        initOfferwall();
        showOfferwall(1000*10);//after 10 seconds
        
        pageinfo_num = (TextView) findViewById(R.id.pageinfo_num);
        pageinfo = (LinearLayout) findViewById(R.id.pageinfo);
        tool = (LinearLayout) findViewById(R.id.tool);
        ((MyApplication) getApplication()).SetPageInfoWidth(tool.getWidth());

        Button btn_add = (Button) findViewById(R.id.main_add);
        btn_add.setOnClickListener(this);
        
        Button feedback = (Button)findViewById(R.id.feedback);
        feedback.setOnClickListener(this);

        Button btn_dele = (Button) findViewById(R.id.main_dele);
        btn_dele.setOnClickListener(this);

        Button btn_cache = (Button) findViewById(R.id.main_cache);
        btn_cache.setOnClickListener(this);

        Button btn_setting = (Button) findViewById(R.id.main_setting);
        btn_setting.setOnClickListener(this);

        LinearLayout rootblock_body = (LinearLayout) findViewById(R.id.rootblock_body);

        myViewGroup = new MyViewGroup(this);

        SharedPreferences p_channel = getSharedPreferences("p_channel", MODE_PRIVATE);
        // p_channel.edit().putString("p_channel_name", "").commit();
        mStrChannel = p_channel.getString("p_channel_name", "");
        // TODO::overwrite whatever
        mStrChannel = "";

        if (mStrChannel == "") {
            String[] channel_init = getResources().getStringArray(R.array.channel_init);
            for (int i = 0; i < channel_init.length; i++) {
                String temp = channel_init[i] + ",1|";
                mStrChannel = mStrChannel + temp;
            }
            p_channel.edit().putString("p_channel_name", mStrChannel).commit();
        }

        String[] arrChannel = mStrChannel.split("\\|");
        for (int i = 0; i < arrChannel.length; i++) {
            String[] temp_arr = arrChannel[i].split(",");
            if (temp_arr != null) {
                if (temp_arr[1] != null) {
                    if (temp_arr[1].equalsIgnoreCase("1")) {
                        mDisplayed.add(temp_arr[0]);
                    } else {
                        mHided.add(temp_arr[0]);
                    }
                }
            }
        }

        InitView();

        myViewGroup.setScrollToScreenCallback(this);
        rootblock_body.addView(myViewGroup);

        // 应用Id 应用密码 广告请求间隔(s) 测试模式
        Util.loadBannerAds(this, R.id.adLayout, kTestMode);
        // 打开积分墙示例(使用积分)
        findViewById(R.id.main_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HappyTimesActivity.this, YoumiOfferwallActivity.class);
                startActivity(intent);
            }
        });
    }

    public void callback(int currentIndex) {
        // TODO Auto-generated method stub
        curScreen = currentIndex + 1;
        new Handler().postDelayed(new Runnable() {
            public void run() {
                // execute the task
                pageinfo_num.setText(curScreen + "");
                applyRotation(0, 180);
            }
        }, 1000);
    }

    /**
     * Setup a new 3D rotation on the container view.
     * 
     * @param start
     *            the start angle at which the rotation must begin
     * @param end
     *            the end angle of the rotation
     */
    private void applyRotation(float start, float end) {
        // Find the center of the container
        final float centerX = pageinfo.getWidth() / 2.0f;
        final float centerY = pageinfo.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, centerX, centerY, 0.0f, true);
        rotation.setDuration(300);

        pageinfo.startAnimation(rotation);
    }

    public void InitView() {
        myViewGroup.removeAllViews();
        int page_num = mDisplayed.size() / 8;
        if (mDisplayed.size() % 8 > 0) {
            page_num++;
        }
        for (int i = 0; i < page_num; i++) {
            FixedGridLayout page = new FixedGridLayout(this);
            for (int j = 0; j < 8; j++) {
                int index = i * 8 + j;
                if (index >= mDisplayed.size()) {
                    break;
                }
                LinearLayout item = (LinearLayout) getLayoutInflater().inflate(R.layout.channel_item, null);
                LinearLayout channel_item_layout = (LinearLayout) item.findViewById(R.id.channel_item_layout);
                channel_item_layout.setTag(mDisplayed.get(index));
                channel_item_layout.setOnClickListener(this);
                channel_item_layout.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {
                        // TODO delete temp
                        // myViewGroup.ShowDelIcon();
                        return true;
                    }
                });
                TextView channel_item_txt = (TextView) item.findViewById(R.id.channel_item_txt);
                channel_item_txt.setText(mDisplayed.get(index));
                ImageView channel_item_remove = (ImageView) item.findViewById(R.id.channel_item_remove);
                channel_item_remove.setTag(mDisplayed.get(index));
                channel_item_remove.setOnClickListener(this);
                if (!mDisplayed.get(index).equalsIgnoreCase("")) {
                    page.addView(item);
                }
            }
            myViewGroup.addView(page);
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.channel_item_remove:
            mDisplayed.remove(v.getTag().toString());
            mHided.add(v.getTag().toString());
            SharedPreferences p_channel = getSharedPreferences("p_channel", MODE_PRIVATE);
            String strTemp = "";
            for (int i = 0; i < mDisplayed.size(); i++) {
                strTemp = strTemp + mDisplayed.get(i) + ",1|";
            }
            for (int i = 0; i < mHided.size(); i++) {
                strTemp = strTemp + mHided.get(i) + ",0|";
            }
            p_channel.edit().putString("p_channel_name", strTemp).commit();
            InitView();
            break;
        case R.id.channel_item_layout:
            ServerDataDecoder key = (ServerDataDecoder) getServerDataDecoder(v.getTag());
            if (null != key) {
                FlurryAgent.logEvent(Util.kFlurryEventOnChannelEntry + key.title());
                Intent intent = new Intent(this, PinterestActivity.class);
                intent.putExtra(ServerDataDecoder.kJsonkeyWrapper, key);
                startActivity(intent);
            }
            break;
        case R.id.main_dele:
            clearCache();
            break;
        case R.id.main_cache:
            cacheChannels();
            break;
        case R.id.main_setting:
            Setting();
            break;
        case R.id.feedback: {
            String kFeedbackEmail = "feedback4iosapp@gmail.com";          
            Util.sendEmail(HappyTimesActivity.this, kFeedbackEmail, getString(R.string.app_name), getString(R.string.feedback_default_content));
        }
            break;

        default:
            break;
        }
    }

    /**
     * 缓存所有频道的数据，包括文字，图片等所有资源
     */
    protected void cacheChannels() {
        Set<String> collection = channel2ClassHashMap.keySet();
        for (Object object : collection) {
            Object instance = getServerDataDecoder((String) object);
            if (null != instance) {
                ServerDataDecoder decoder = (ServerDataDecoder) instance;
                ChannelRequest request = new ChannelRequest(decoder);
                request.get(decoder.url(1));
                request.setCache(MyApplication.getCache());
                RequestQueue.instanceForLongRequestQueue().push(request);
            }

        }
    }

    Object getServerDataDecoder(Object channelName) {
        if (channelName instanceof String) {
            Class className = channel2ClassHashMap.get(channelName);
            if (null != className) {
                try {
                    return className.newInstance();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (myViewGroup.IsShowDelIcon()) {
                myViewGroup.ShowDelIcon();
                return true;
            } else {
                Exit();
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    void Exit() {
        Builder bExit = new AlertDialog.Builder(this);
        bExit.setTitle(R.string.exist_tip_title);
        bExit.setMessage(R.string.exist_tip_message);
        bExit.setPositiveButton(android.R.string.ok, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                HappyTimesActivity.this.finish();
            }
        });
        bExit.setNegativeButton(android.R.string.cancel, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        bExit.create().show();
    }

    void Refresh() {

    }

    void clearCache() {
        Builder bDele = new AlertDialog.Builder(this);
        bDele.setTitle(R.string.clear_cache_tip);
        bDele.setMessage(R.string.clear_cache_message);
        bDele.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progessbar);
                progressBar.setVisibility(View.VISIBLE);

                RequestQueue.instance().push(new Runnable() {
                    @Override
                    public void run() {
                        MyApplication.getCache().clear();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                            }
                        });
                    }
                });
            }
        });
        bDele.setNegativeButton(android.R.string.cancel, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        bDele.create().show();
    }

    void Setting() {
        Intent intent = new Intent(getApplicationContext(), SettingActivity.class);
        startActivity(intent);
    }

    void Add() {

    }
}